package org.lk.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.lk.reggie.common.BaseContext;
import org.lk.reggie.common.R;
import org.lk.reggie.entity.ShoppingCart;
import org.lk.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingController
{

    @Autowired
    ShoppingCartService shoppingCartService;

    @PostMapping("/add")
    public R<ShoppingCart> add(@RequestBody ShoppingCart shoppingCart)
    {
        ShoppingCart res = new ShoppingCart();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        // 获取当前用户的 id
        Long userId = BaseContext.getCurrentId();
        shoppingCart.setUserId(userId);
        // 查询当前菜品或套餐是否在购物车中，
        queryWrapper.eq(ShoppingCart :: getUserId, userId);
        if (shoppingCart.getDishId() != null)
        {
            // 是菜品
            queryWrapper.eq(ShoppingCart :: getDishId, shoppingCart.getDishId());
        }
        else
        {
            // 是套餐
            queryWrapper.eq(ShoppingCart :: getSetmealId, shoppingCart.getSetmealId());
        }
        res = addDishOrSetmeal(queryWrapper, shoppingCart);


        // 不存在添加至购物车 number 默认为 1
        return R.success(res);
    }


    @GetMapping("/list")
    public R<List<ShoppingCart>> getAllShoppingCart()
    {
        Long currentId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart :: getUserId, currentId);
        List<ShoppingCart> list = shoppingCartService.list(queryWrapper);
        return R.success(list);
    }

    @DeleteMapping("/clean")
    public R<String> cleanShopping()
    {
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart :: getUserId, userId);
        shoppingCartService.remove(queryWrapper);
        return R.success("success");
    }


    public ShoppingCart addDishOrSetmeal(LambdaQueryWrapper<ShoppingCart> queryWrapper, ShoppingCart shoppingCart)
    {
        ShoppingCart one = shoppingCartService.getOne(queryWrapper);
        if (one != null)
        {
            // 有的话 number ++
            Integer number = one.getNumber();
            number ++;
            one.setNumber( number);
            shoppingCartService.updateById(one);
        }
        else
        {
            shoppingCart.setNumber(1);
            shoppingCartService.save(shoppingCart);
            one = shoppingCart;
        }
        return one;
    }
}
